package kim.artemis.rpc.core.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import kim.artemis.rpc.core.protocol.serializer.ArtemisSerializer;

/**
 * 编码
 * @author Wq.
 */
public class ArtemisEncoder extends MessageToByteEncoder<Object> {

    private Class<?> classz;
    private ArtemisSerializer serializer;

    public ArtemisEncoder(Class<?> classz, ArtemisSerializer serializer) {
        this.classz = classz;
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext handlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (classz.isInstance(o)) {
            byte[] data = serializer.serialize(o);
            byteBuf.writeInt(data.length);
            byteBuf.writeBytes(data);
        }
    }
}
